import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '../views/Main/Main.vue'
import store from '@/store'
import Home from '../views/Menus/Home/Home.vue'
import userInfo from '../views/Menus/User/UserInfo.vue'
import UserAvater from '../views/Menus/User/UserAvater.vue'
import UserPwd from '../views/Menus/User/UserPwd.vue'
import ArtCate from '../views/Menus/Artcle/ArtCate.vue'
import ArtList from '../views/Menus/Artcle/ArtList.vue'
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    // 设置路由的重定向
    redirect: '/home',
    // 配置二级路由规则
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: userInfo },
      // 设置用户上传头像挂载点
      { path: 'user-avatar', component: UserAvater },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }

    ]
  }
]

const router = new VueRouter({
  routes
})
// 没有 token 时，禁止访问后台主页
// 添加前置的路由守卫
router.beforeEach((to, from, next) => {
// 登录的判断依据：是否有tokn
  const token = store.state.user.token
  // 设置白名单
  const whilteList = ['/login', '/reg']
  if (!token && !whilteList.includes(to.path)) {
    // 如果没有token，并且在白名单内，那么强行跳转到登录页
    next('/login')
  } else {
    // 直接放行
    next()
  }
})
export default router
